using System;
using System.Collections.Specialized;
using AspNetMvc.Exceptions;
using AspNetMvc.Helpers;
using AspNetMvc.Services.Events.Interfaces;
using CoreVirtuoso.Config;
using PublicDomain.ZoneInfo;
using WebGuiMvc.Helpers;

namespace AspNetMvc.Services.Events
{
   public class EventDatesPostParser : IEventDatesPostParser
   {
      public DateTimeOffset? Parse(NameValueCollection collection,
                           string dateName,
                           string hoursName,
                           string minutesName,
                           Zone zone,
                           string incorrectDateFormatError,
                           string incorrectTimeFormatError,
                           string incorrectDateTimeError)
      {
         try
         {
            string dateString = PostValuesRetrievingHelper.GetValue(collection, dateName);
            string hoursString = PostValuesRetrievingHelper.GetValue(collection, hoursName);
            string minutesString = PostValuesRetrievingHelper.GetValue(collection, minutesName);
            if (String.IsNullOrEmpty(dateString) || dateString == DummyItemsConfig.DummyItemValue ||
               String.IsNullOrEmpty(hoursString) || hoursString == DummyItemsConfig.DummyItemValue ||
               String.IsNullOrEmpty(minutesString) || minutesString == DummyItemsConfig.DummyItemValue)
               return null;

            int year;
            int month;
            int day;
            bool dateMatches = DateStringParseHelper.Parse(dateString, out year, out month, out day);
            //ToDo: It would be better to write which of dates is incorrect.
            if (!dateMatches)
               throw new ValidationException(incorrectDateFormatError);

            int hours = Int32.Parse(hoursString);

            int minutes = Int32.Parse(minutesString);

            DateTime dateTime = new DateTime(year, month, day,
                                             hours, minutes, 0);
            TimeSpan utcOffset = zone.GetUtcOffset(dateTime);
            return new DateTimeOffset(dateTime, utcOffset);
         }
         catch (Exception ex)
         {
            throw new ValidationException(incorrectDateTimeError);
         }
      }
   }
}